package org.example.lock;

import com.alibaba.ttl.TransmittableThreadLocal;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessLock;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * @author shenguangyang
 */
@Component
public class CuratorLock extends LockTemplate {
    private static final Logger log = LoggerFactory.getLogger(CuratorLock.class);
    protected static final String DEFAULT_LOCKS_PATH = "/locks";
    protected String lockPath;

    @Resource
    protected CuratorFramework curatorFramework;

    private static final TransmittableThreadLocal<InterProcessLock> interProcessMutexTtl = new TransmittableThreadLocal<>();

    @PostConstruct
    public void init() {
        this.lockPath = DEFAULT_LOCKS_PATH;
    }

    @Override
    public void unlock() {
        InterProcessLock lock = interProcessMutexTtl.get();
        if (lock != null) {
            try {
                lock.release();
            } catch (Exception e) {
                log.error("unlock fail, error: ", e);
            }
        }
    }

    @Override
    protected boolean tryLock() {
        InterProcessLock lock = interProcessMutexTtl.get();
        if (lock == null) {
            lock = new InterProcessMutex(curatorFramework, this.lockPath);
            interProcessMutexTtl.set(lock);
        }
        try {
            return lock.acquire(5, TimeUnit.SECONDS);
        } catch (Exception e) {
            log.error("try get lock fail, error: ", e);
        }
        return false;
    }

    @Override
    protected void waitLock() {

    }
}
